#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include "test_utils.h"

long long recv_bytes;
long long recv_count;

void* print_stat(void*)
{
    long long sec = 0;
    while (true)
    {
        sleep(1);
        sec++;

        long long n_bytes = recv_bytes;
        recv_bytes = 0;

        long long n_count = recv_count;
        recv_count = 0;

        printf("%lld: \t count: %lld \t thr(MB): %lld\n",
            sec,
            n_count,
            n_bytes/1024/1024);
    }

    return 0;
}

static int set_reuse_addr(int fd)
{
    int reuse = 1;
    return setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));		
}

int main(int argc, char** argv)
{
    int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    errno_assert(listen_fd != -1);

    int rc = set_reuse_addr(listen_fd);
    errno_assert(rc == 0);

    sockaddr_in addr  = {};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(2650);

    rc = bind(listen_fd, (sockaddr*)&addr, sizeof(addr));
    errno_assert(rc == 0);

    rc = listen(listen_fd, 1);
    errno_assert(rc == 0);

    int child_fd = -1;
    char buf[2*1024*1024];

    child_fd = accept(listen_fd, 0, 0);
    errno_assert(child_fd != -1);
    
    printf("new connection accepted, start recv...\n");
    
    pthread_t tid;
    rc = pthread_create(&tid, 0, print_stat, 0);
    posix_assert(rc == 0);    

    while (true)
    {
    	int len = recv(child_fd, buf, sizeof(buf), 0);        
    	if (len <= 0)
    		break;
    		
    	recv_count++;
    	recv_bytes += len;	
    }

    printf("recv completed, close connection now.\n");

    rc = close(child_fd);
    errno_assert(rc == 0);

    rc = close(listen_fd);
    errno_assert(rc == 0);

    return 0;
}

